package com.cet.programmercarl.algorithmperformancanalysis.字符串;

/**
 * @program: algorithm
 * @description: strStr()问题
 * @author: 陈恩涛
 * @create: 2022-03-21 18:02
 **/
public class LC28 {

    /**
     * 返回haystack中首次出现needle的位置
     * 找不到返回-1，当needle为空字符串时返回0
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int i;
        int j;
        int hLength = haystack.length();
        int nLength = needle.length();

        for (i = 0, j = 0; i < hLength && j < nLength; i++) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            } else {
                i -= j;
                j = 0;
            }
        }
        if (j == nLength) {
            return i - j;
        } else {
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println(strStr("abacadabraac", "abra"));
    }
}
